package com.xiaohudie.SGGJUC;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author xiao hu die
 * @Date 2022/3/12 13:25
 * @Version 1.0
 */
/**使用原子类来解决原子类问题*/
public  class  TestVolatile2 {
    /**volatile不保证原子性*/
    private  static AtomicInteger num =new AtomicInteger();
   // static Lock lock =  new ReentrantLock();
    public  static void add(){
    // lock.lock();
    //try {
       // num++;//不是原子操作
    //}finally {
      //  lock.unlock();
    num.getAndIncrement();

    }

    public  static void main(String[] args) {
        for (int i = 0; i <20 ; i++) {
            new Thread(()->{
                for (int j = 0; j <1000 ; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(num);
    }
}
